package com.maori.languageapp.discover;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import com.maori.languageapp.LanguageAppCaptureActivity;
import com.maori.languageapp.Languageapp_Discover_Videolist_Adapter;
import com.maori.languageapp.Maori_MainActivity;
import com.maori.languageapp.R;
import com.maori.languageapp.UploadToFtp;
import com.maori.languageapp.UploadToFtpAudio;
import com.maori.languageapp.UploadToFtpVideo;
import com.maori.languageapp.adapter.Language_App_List_Exapander;
import com.maori.languageapp.consts.CaptureFilterAdapter;
import com.maori.languageapp.consts.ImageLoader;
import com.maori.languageapp.consts.UrlContant;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.AdapterView.OnItemClickListener;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@SuppressLint("NewApi")
public class Maori_Discover_Word_Details extends Activity {
	// Database Name
	private static final String DATABASE_NAME = "maorilanguageapp.db";
	private String BOOKMARK_TABLE = "Bookmark";
	protected static final String TAG = null;
	String word, maori, nid, Source;
	private CaptureFilterAdapter dbHelper;
	private SimpleCursorAdapter dataAdapter;
	ProgressDialog mProgressDialog;
	Bitmap bmImg = null;
	Bitmap userbmImg = null;
	InputStream is = null;
	StringBuilder sb = null;

	String result;
	JSONArray jArray;
	HttpParams httpParameters = new BasicHttpParams();
	String LastDownloadUpdateTime;
	TextView txtHeading;
	int timeoutConnection = 5000;
	JSONArray jsonarray;
	SQLiteDatabase mydb;
	ListView listview;
	private Bitmap bitmap;
	int HeaderBtnTag = 0;
	int TotalsSynonimValue = 0, TotalsSynonimImagesValue = 0,
			TotalsSynonimVideoValue = 0;
	// Adapter Objects
	Maori_Discover_Word_Details_Adapter adapter;
	Maori_Discover_Word_AudioList_Adapter adapterAudio;
	Maori_Discover_Word_ImageList_Adapter adapterImages;
	Maori_Discover_Word_VideoList_Adapter adapterVideos;
	static String Description_a = "Description_a";
	static String Description_b = "Description_b";
	static String UIDuser = "UIDuser";
	static String first_name = "first_name";
	static String last_name = "last_name";
	static String tribe = "tribe";
	static String userimage = "MID";
	static String UID = "UID";
	static String NID = "nid";
	static String MID = "MID";
	static String M_Source = "M_Source";
	static String SYNNID = "SYNNID";

	static String first_namesuser = "first_namesuser";
	static String last_nameuser = "last_nameuser";
	static String tribeuser = "tribeuser";
	static String userimageuser = "userimageuser";

	static String TotalsLikes = "TotalsLikes";
	static String TotalsSynonim = "TotalsSynonim";
	static String TotalImages = "TotalImages";
	static String TotalAudios = "TotalAudios";
	static String TotalVideos = "TotalVideos";

	static String TotalsLikesSyn = "TotalsLikesSyn";
	static String TotalsLikesImage = "TotalsLikesImage";
	
	
	static String IMAGENM_ID = "IMAGENM_ID";
	static String IMAGENID = "IMAGENID";
	static String IMAGEMID = "IMAGEMID";
	static String IMAGEUID = "IMAGEUID";
	static String IMAGEM_Source = "IMAGEM_Source";
	static String IMAGEfirst_name = "IMAGEfirst_name";
	static String IMAGElast_name = "IMAGElast_name";
	static String IMAGETotalsLikes = "IMAGETotalsLikes";
	

	int AudioDownFlg = 0;
	// Save Image,Audio Video Paths
	private String MEDIA_FILE_URL = "MediaFileUrl";

	ArrayList<HashMap<String, String>> arraylist;
	ArrayList<HashMap<String, String>> audioArrayList;
	ArrayList<HashMap<String, String>> imagesArrayList;
	ArrayList<HashMap<String, String>> videoArrayList;

	// Tabs Option Display
	Button wordsynonyms, wordaudio, wordimages, wordvideo;
	Button btnsearchexcisting, btnaddnewsynonim, submitbtnsynonim;
	Button btnbookmarknode, btnsharenode, btnlikenode, btnplaynode;
	// Image capturing Handlers
	String filemanagerstring;
	String selectedImagePath;
	ImageView SynonymImages;
	Uri selectedImageUri;
	String filePath, currentVideoName;
	private String tempDir;
	VideoView videoPreview;
	private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
	private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;
	private Uri fileUri;
	private static final int PICK_IMAGE = 1;
	private static final String IMAGE_DIRECTORY_NAME = "lANGUAGEAPP";
	ImageButton btnviewsynonims;
	Button capture_camera_button, capture_gallery_button, videorecord_button,
			cancelbtn;

	EditText etmaorisynonimword, etenglishsynonimword;
	LinearLayout capturesynonims, searchviewarea, captureActionControllers,
			capturesynonimsaudio, capturesynonimsimages, capturesynonimsvideo,
			camvideoparent;
	ListView listViewSynonyms, listViewExcistingSynonyms,
			listViewAudioSynonyms, listViewImageSynonyms,
			listViewVideoSynonyms;

	String saveSaveSynonimAUrl, UserID, currentImageName;

	/**** Selection Identifires ****/
	int SynonimTag = 0, AudioTag = 0, ImageTag = 0, VideoTag = 0;
    int reloadTAG;
    String reloadREFNO;
    // Discover Audio Uploading Option
	Button record_button, play_button;
	int recordActive = 0;
	int recordPlay = 0;
	int loadCounter = 0;
	private String outputFile = null;
	// Media resource path
	String AudioMainPath;
	String currentAudioName = "2=AUDIO";
	private MediaRecorder myRecorder;
	private MediaPlayer myPlayer;
	static String upladingFromPath, sourceUrl;
	static String filename;
	String desDirectory = "http://langapp.testarea.co.nz:2082/lanappaudio/";
	EditText searchfiltertext;
	String LikeRefId;
	int LikeCategory = 0;

	public void LikeSynonim(View view) {
		final Animation anima = AnimationUtils.loadAnimation(this,
				R.anim.btnzoominout);
		view.startAnimation(anima);
		Button des = (Button) view;
		LikeCategory = 0;
		LikeRefId = des.getText().toString();
		new loadSingleViewSyn().execute();
		Toast.makeText(getApplicationContext(), "LIKE NID : " + LikeRefId,
				Toast.LENGTH_LONG).show();
	}
	
	public void LikeSynonimImage(View view) {
		final Animation anima = AnimationUtils.loadAnimation(this,
				R.anim.btnzoominout);
		view.startAnimation(anima);
		Button des = (Button) view;
		LikeCategory = 1;
		LikeRefId = des.getText().toString();
		new loadSingleViewSynImage().execute();
		
		Toast.makeText(getApplicationContext(), "LIKE NID : " + LikeRefId,
				Toast.LENGTH_LONG).show();
	}
	
	public void SetDefaultImage(View view) {
		final Animation anima = AnimationUtils.loadAnimation(this,
				R.anim.btnzoominout);
		view.startAnimation(anima);
		Button des = (Button) view;
		LikeCategory = 1;
		LikeRefId = des.getText().toString();
		new loadDefaultImage().execute();
		
		Toast.makeText(getApplicationContext(), "LIKE NID : " + LikeRefId,
				Toast.LENGTH_LONG).show();
	}
	
	

	public void SetDefault(View view) {
		final Animation anima = AnimationUtils.loadAnimation(this,
				R.anim.btnzoominout);
		view.startAnimation(anima);
		Button des = (Button) view;
		LikeRefId = des.getText().toString();
		Toast.makeText(getApplicationContext(), "SET DEF NID : " + LikeRefId,
				Toast.LENGTH_LONG).show();
	}

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Remove title bar
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.maori_discover_word_details);
		txtHeading = (TextView) findViewById(R.id.txtHeading);
		txtHeading.setText("Discover Word Details");
		dbHelper = new CaptureFilterAdapter(this);
		dbHelper.open();
		saveSaveSynonimAUrl = UrlContant.SaveSynonimCategoryAUrl;
		// Layout objects for cature new synonims
		capturesynonims = (LinearLayout) findViewById(R.id.capturesynonims);
		// Display Search Area
		searchviewarea = (LinearLayout) findViewById(R.id.searchviewarea);
		// Display Synonyms
		listViewSynonyms = (ListView) findViewById(R.id.listViewSynonyms);
		listViewExcistingSynonyms = (ListView) findViewById(R.id.listViewExcistingSynonyms);
		// Display Audio Synonyms
		listViewAudioSynonyms = (ListView) findViewById(R.id.listViewAudioSynonyms);
		// Display Image Synonyms
		listViewImageSynonyms = (ListView) findViewById(R.id.listViewImageSynonyms);
		// Display Video Synonyms
		listViewVideoSynonyms = (ListView) findViewById(R.id.listViewVideoSynonyms);
		// add new audio options block
		capturesynonimsaudio = (LinearLayout) findViewById(R.id.capturesynonimsaudio);
		// add new image option block
		capturesynonimsimages = (LinearLayout) findViewById(R.id.capturesynonimsimages);
		// add new video option block
		capturesynonimsvideo = (LinearLayout) findViewById(R.id.capturesynonimsvideo);
		camvideoparent = (LinearLayout) findViewById(R.id.camvideoparent);
		// Capture Controlling Buttons
		captureActionControllers = (LinearLayout) findViewById(R.id.captureActionControllers);

		// Search Box Action
		searchfiltertext = (EditText) findViewById(R.id.searchfiltertext);
		// Bar action controllers
		wordsynonyms = (Button) findViewById(R.id.wordsynonyms);
		wordaudio = (Button) findViewById(R.id.wordaudio);
		wordimages = (Button) findViewById(R.id.wordimages);
		wordvideo = (Button) findViewById(R.id.wordvideo);

		// Header sub option handling Buttons click
		btnbookmarknode = (Button) findViewById(R.id.btnbookmarknode);
		btnsharenode = (Button) findViewById(R.id.btnsharenode);
		btnlikenode = (Button) findViewById(R.id.btnlikenode);
		btnplaynode = (Button) findViewById(R.id.btnplaynode);

		videorecord_button = (Button) findViewById(R.id.videorecord_button);
		capture_camera_button = (Button) findViewById(R.id.capture_camera_button);
		capture_gallery_button = (Button) findViewById(R.id.capture_gallery_button);
		// Display Allocated Layout Frames
		btnsearchexcisting = (Button) findViewById(R.id.btnsearchexcisting);
		btnviewsynonims = (ImageButton) findViewById(R.id.btnviewsynonims);
		btnaddnewsynonim = (Button) findViewById(R.id.btnaddnewsynonim);
		videoPreview = (VideoView) findViewById(R.id.videoview);
		// Uploading Data Inputs
		etmaorisynonimword = (EditText) findViewById(R.id.etmaorisynonimword);
		etenglishsynonimword = (EditText) findViewById(R.id.etenglishsynonimword);

		// Server Uploading Handlers
		submitbtnsynonim = (Button) findViewById(R.id.submitbtnsynonim);

		SynonymImages = (ImageView) findViewById(R.id.synonymImageView);
		/********** Audio Configuring ***************/
		// Button View Controllers
		record_button = (Button) findViewById(R.id.record_button);
		play_button = (Button) findViewById(R.id.play_button);

		/****** Set as default with selected Option *********/
		wordsynonyms.setBackgroundResource(R.color.CLR_ORANGE);
		btnviewsynonims.setImageResource(R.drawable.iconj);
		listViewSynonyms.setVisibility(LinearLayout.VISIBLE);
		SynonimTag = 202;
		getCurrentUserDetails();
		// Cancel Current View and Exit
		cancelbtn = (Button) findViewById(R.id.cancelbtn);
		cancelbtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				displayCancelDialog();
			}
		});

		new loadSingleView().execute();

		// Header Sub Option Panel Button Click Event Handling

		/************* Button animation *************/
		final View vbookmark = findViewById(R.id.btnbookmarknode);
		final Animation anima = AnimationUtils.loadAnimation(this,
				R.anim.btnzoominout);
		final View vshare = findViewById(R.id.btnsharenode);
		final Animation animb = AnimationUtils.loadAnimation(this,
				R.anim.btnzoominout);
		final View vlike = findViewById(R.id.btnlikenode);
		final Animation animc = AnimationUtils.loadAnimation(this,
				R.anim.btnzoominout);
		final View vplay = findViewById(R.id.btnplaynode);
		final Animation animd = AnimationUtils.loadAnimation(this,
				R.anim.btnzoominout);

		btnbookmarknode.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				HeaderBtnTag = 100;
				vbookmark.startAnimation(anima);
				new UploadBookMarkDetails().execute();
				saveBookMarkDetails();
			}
		});
		btnsharenode.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				HeaderBtnTag = 200;
				vshare.startAnimation(animb);
				Toast.makeText(getApplicationContext(),
						"Share.." + nid + "/" + UserID, Toast.LENGTH_LONG)
						.show();
			}
		});
		btnlikenode.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				HeaderBtnTag = 300;
				vlike.startAnimation(animc);
				new UploadBookMarkDetails().execute();
			}
		});
		btnplaynode.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				HeaderBtnTag = 400;
				vplay.startAnimation(animd);
				Toast.makeText(getApplicationContext(),
						"Play.. " + nid + "/" + UserID, Toast.LENGTH_LONG)
						.show();
			}
		});

		/************** Data Display Filter Options **************/
		btnaddnewsynonim.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// int SynonimTag = 0, AudioTag = 0, ImageTag = 0, VideoTag = 0;
				if (SynonimTag == 202) {
					/********* Make Related View Visible True *************/
					capturesynonims.setVisibility(LinearLayout.VISIBLE);
					captureActionControllers
							.setVisibility(LinearLayout.VISIBLE);
					capturesynonimsvideo.setVisibility(LinearLayout.GONE);
					camvideoparent.setVisibility(LinearLayout.GONE);
					searchviewarea.setVisibility(LinearLayout.GONE);
					listViewSynonyms.setVisibility(LinearLayout.GONE);
					listViewAudioSynonyms.setVisibility(LinearLayout.GONE);
					listViewImageSynonyms.setVisibility(LinearLayout.GONE);
					/********* Make Other Views Visible Gone *************/
				} else if (AudioTag == 202) {
					capturesynonimsaudio.setVisibility(LinearLayout.VISIBLE);
					captureActionControllers
							.setVisibility(LinearLayout.VISIBLE);
					capturesynonimsvideo.setVisibility(LinearLayout.GONE);
					camvideoparent.setVisibility(LinearLayout.GONE);
					searchviewarea.setVisibility(LinearLayout.GONE);
					listViewAudioSynonyms.setVisibility(LinearLayout.GONE);
					listViewSynonyms.setVisibility(LinearLayout.GONE);
					listViewImageSynonyms.setVisibility(LinearLayout.GONE);
				} else if (ImageTag == 202) {
					capturesynonimsimages.setVisibility(LinearLayout.VISIBLE);
					captureActionControllers
							.setVisibility(LinearLayout.VISIBLE);

					capturesynonimsvideo.setVisibility(LinearLayout.GONE);
					camvideoparent.setVisibility(LinearLayout.GONE);
					capturesynonimsaudio.setVisibility(LinearLayout.GONE);
					searchviewarea.setVisibility(LinearLayout.GONE);
					listViewAudioSynonyms.setVisibility(LinearLayout.GONE);
					listViewSynonyms.setVisibility(LinearLayout.GONE);
					listViewImageSynonyms.setVisibility(LinearLayout.GONE);
				} else if (VideoTag == 202) {
					capturesynonimsvideo.setVisibility(LinearLayout.VISIBLE);
					camvideoparent.setVisibility(LinearLayout.VISIBLE);
					captureActionControllers
							.setVisibility(LinearLayout.VISIBLE);

					capturesynonimsaudio.setVisibility(LinearLayout.GONE);
					searchviewarea.setVisibility(LinearLayout.GONE);
					listViewAudioSynonyms.setVisibility(LinearLayout.GONE);
					listViewSynonyms.setVisibility(LinearLayout.GONE);
					listViewImageSynonyms.setVisibility(LinearLayout.GONE);
				}
			}
		});

		btnviewsynonims.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (SynonimTag == 202) {
					/********* Make Related View Visible True *************/
					listViewSynonyms.setVisibility(LinearLayout.VISIBLE);

					/********* Make Other Views Visible Gone *************/
					listViewAudioSynonyms.setVisibility(LinearLayout.GONE);
					listViewImageSynonyms.setVisibility(LinearLayout.GONE);
					capturesynonims.setVisibility(LinearLayout.GONE);
					captureActionControllers.setVisibility(LinearLayout.GONE);
					searchviewarea.setVisibility(LinearLayout.GONE);
				}

				else if (AudioTag == 202) {
					/********* Make Related View Visible True *************/
					listViewAudioSynonyms.setVisibility(LinearLayout.VISIBLE);

					/********* Make Other Views Visible Gone *************/
					listViewSynonyms.setVisibility(LinearLayout.GONE);
					listViewImageSynonyms.setVisibility(LinearLayout.GONE);
					capturesynonims.setVisibility(LinearLayout.GONE);
					captureActionControllers.setVisibility(LinearLayout.GONE);
					searchviewarea.setVisibility(LinearLayout.GONE);
				}

				else if (ImageTag == 202) {
					/********* Make Related View Visible True *************/
					listViewImageSynonyms.setVisibility(LinearLayout.VISIBLE);

					/********* Make Other Views Visible Gone *************/
					listViewAudioSynonyms.setVisibility(LinearLayout.GONE);
					listViewSynonyms.setVisibility(LinearLayout.GONE);
					capturesynonims.setVisibility(LinearLayout.GONE);
					captureActionControllers.setVisibility(LinearLayout.GONE);
					searchviewarea.setVisibility(LinearLayout.GONE);
				}

				else if (VideoTag == 202) {
					/********* Make Related View Visible True *************/

					/********* Make Other Views Visible Gone *************/
					listViewImageSynonyms.setVisibility(LinearLayout.GONE);
					listViewAudioSynonyms.setVisibility(LinearLayout.GONE);
					capturesynonims.setVisibility(LinearLayout.GONE);
					captureActionControllers.setVisibility(LinearLayout.GONE);
					searchviewarea.setVisibility(LinearLayout.GONE);
				}
			}
		});
		btnsearchexcisting.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (SynonimTag == 202) {
					loadWordsDetailsList();
					capturesynonims.setVisibility(LinearLayout.GONE);
					captureActionControllers.setVisibility(LinearLayout.GONE);
					searchviewarea.setVisibility(LinearLayout.VISIBLE);
					listViewExcistingSynonyms
							.setVisibility(LinearLayout.VISIBLE);
					listViewSynonyms.setVisibility(LinearLayout.GONE);
					listViewAudioSynonyms.setVisibility(LinearLayout.GONE);
				} else if (AudioTag == 202) {
					capturesynonims.setVisibility(LinearLayout.GONE);
					captureActionControllers.setVisibility(LinearLayout.GONE);
					searchviewarea.setVisibility(LinearLayout.VISIBLE);
					listViewAudioSynonyms.setVisibility(LinearLayout.VISIBLE);
					listViewSynonyms.setVisibility(LinearLayout.GONE);
					listViewExcistingSynonyms.setVisibility(LinearLayout.GONE);
				} else if (ImageTag == 202) {

				} else if (VideoTag == 202) {

				}
			}
		});

		/******* Upload Word Synonyms ******/
		submitbtnsynonim.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (VideoTag == 202) {
					if (isNetworkAvailable()) {
						new UploadVideoDetails().execute();

					} else {

					}
				}
				if (AudioTag == 202) {
					if (isNetworkAvailable()) {
						new UploadAudioDetails().execute();

					} else {

					}
				}
				if (ImageTag == 202) {
					if (isNetworkAvailable()) {
						new UploadImageDetails().execute();

					} else {

					}

				}
				if (SynonimTag == 202) {
					new UploadingSynonimDetails().execute();
				}

			}
		});

		/*********** Tabs Options Handlers ***********/
		wordsynonyms.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				SynonimTag = 202;
				AudioTag = 0;
				ImageTag = 0;
				VideoTag = 0;

				btnviewsynonims.setImageResource(R.drawable.iconj);

				wordsynonyms.setBackgroundResource(R.color.CLR_ORANGE);
				wordaudio.setBackgroundResource(R.color.CLR_SKYBLUE);
				wordimages.setBackgroundResource(R.color.CLR_SKYBLUE);
				wordvideo.setBackgroundResource(R.color.CLR_SKYBLUE);

				/********** Display Panels **********************/
				listViewImageSynonyms.setVisibility(LinearLayout.GONE);
				listViewVideoSynonyms.setVisibility(LinearLayout.GONE);
				capturesynonims.setVisibility(LinearLayout.GONE);
				listViewSynonyms.setVisibility(LinearLayout.VISIBLE);
				listViewExcistingSynonyms.setVisibility(LinearLayout.GONE);
				searchviewarea.setVisibility(LinearLayout.GONE);
				listViewAudioSynonyms.setVisibility(LinearLayout.GONE);
				capturesynonimsaudio.setVisibility(LinearLayout.GONE);
				capturesynonimsvideo.setVisibility(LinearLayout.GONE);
				camvideoparent.setVisibility(LinearLayout.GONE);
				/********** Hide Panels **********************/

			}
		});
		wordaudio.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				SynonimTag = 0;
				AudioTag = 202;
				ImageTag = 0;
				VideoTag = 0;

				btnviewsynonims.setImageResource(R.drawable.micon);
				wordsynonyms.setBackgroundResource(R.color.CLR_SKYBLUE);
				wordaudio.setBackgroundResource(R.color.CLR_ORANGE);
				wordimages.setBackgroundResource(R.color.CLR_SKYBLUE);
				wordvideo.setBackgroundResource(R.color.CLR_SKYBLUE);

				/********** Display Panels **********************/
				listViewAudioSynonyms.setVisibility(LinearLayout.VISIBLE);
				capturesynonimsaudio.setVisibility(LinearLayout.GONE);
				/********** Hide Panels **********************/
				listViewImageSynonyms.setVisibility(LinearLayout.GONE);
				captureActionControllers.setVisibility(LinearLayout.GONE);
				capturesynonims.setVisibility(LinearLayout.GONE);
				searchviewarea.setVisibility(LinearLayout.GONE);
				listViewSynonyms.setVisibility(LinearLayout.GONE);
				listViewExcistingSynonyms.setVisibility(LinearLayout.GONE);
				listViewVideoSynonyms.setVisibility(LinearLayout.GONE);
				capturesynonimsvideo.setVisibility(LinearLayout.GONE);
				camvideoparent.setVisibility(LinearLayout.GONE);
			}
		});

		wordimages.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				SynonimTag = 0;
				AudioTag = 0;
				ImageTag = 202;
				VideoTag = 0;

				btnviewsynonims.setImageResource(R.drawable.photoon);
				wordsynonyms.setBackgroundResource(R.color.CLR_SKYBLUE);
				wordaudio.setBackgroundResource(R.color.CLR_SKYBLUE);
				wordimages.setBackgroundResource(R.color.CLR_ORANGE);
				wordvideo.setBackgroundResource(R.color.CLR_SKYBLUE);

				/********** Display Panels **********************/

				/********** Hide Panels **********************/
				listViewImageSynonyms.setVisibility(LinearLayout.VISIBLE);
				captureActionControllers.setVisibility(LinearLayout.GONE);
				capturesynonims.setVisibility(LinearLayout.GONE);
				searchviewarea.setVisibility(LinearLayout.GONE);
				listViewVideoSynonyms.setVisibility(LinearLayout.GONE);
				listViewSynonyms.setVisibility(LinearLayout.GONE);
				listViewAudioSynonyms.setVisibility(LinearLayout.GONE);
				capturesynonimsaudio.setVisibility(LinearLayout.GONE);
				listViewExcistingSynonyms.setVisibility(LinearLayout.GONE);
				capturesynonimsvideo.setVisibility(LinearLayout.GONE);
				camvideoparent.setVisibility(LinearLayout.GONE);
			}
		});

		wordvideo.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				SynonimTag = 0;
				AudioTag = 0;
				ImageTag = 0;
				VideoTag = 202;
				btnviewsynonims.setImageResource(R.drawable.camvideoon);
				wordsynonyms.setBackgroundResource(R.color.CLR_SKYBLUE);
				wordaudio.setBackgroundResource(R.color.CLR_SKYBLUE);
				wordimages.setBackgroundResource(R.color.CLR_SKYBLUE);
				wordvideo.setBackgroundResource(R.color.CLR_ORANGE);

				/********** Display Panels **********************/

				/********** Hide Panels **********************/
				listViewVideoSynonyms.setVisibility(LinearLayout.VISIBLE);
				listViewImageSynonyms.setVisibility(LinearLayout.GONE);
				captureActionControllers.setVisibility(LinearLayout.GONE);
				capturesynonims.setVisibility(LinearLayout.GONE);
				searchviewarea.setVisibility(LinearLayout.GONE);
				listViewSynonyms.setVisibility(LinearLayout.GONE);
				listViewAudioSynonyms.setVisibility(LinearLayout.GONE);
				capturesynonimsaudio.setVisibility(LinearLayout.GONE);
				listViewExcistingSynonyms.setVisibility(LinearLayout.GONE);
				capturesynonimsvideo.setVisibility(LinearLayout.GONE);
				camvideoparent.setVisibility(LinearLayout.GONE);
			}
		});

		/*************** Audio Recording Handlers **************************/
		// ***** Recording Audio Function
		record_button.setOnClickListener(new View.OnClickListener() {
			@SuppressLint("NewApi")
			public void onClick(View view) {

				if (recordActive == 0) {
					recordActive = 1;
					// Audio Recording
					// store it to sd card
					record_button.setBackground(getResources().getDrawable(
							R.drawable.recordstop_button));
					outputFile = Environment.getExternalStorageDirectory()
							.getAbsolutePath()
							+ "/"
							+ getAudiorecording().toString() + ".mp4";
					AudioMainPath = Environment.getExternalStorageDirectory()
							.getAbsolutePath() + "/";
					currentAudioName = getAudiorecording().toString() + ".mp4";
					myRecorder = new MediaRecorder();
					myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
					myRecorder
							.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
					myRecorder
							.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);

					myRecorder.setOutputFile(outputFile);
					/* currentAudioName = "2=AUDIO"; */
					Log.v(TAG, "AUDIO PATH : " + outputFile);
					saveMediaFileDetails();
					play_button.setEnabled(false);
					start(view);
				} else if (recordActive == 1) {
					recordActive = 0;
					record_button.setBackground(getResources().getDrawable(
							R.drawable.record_button));
					play_button.setEnabled(true);
					stop(view);
				}

			}
		});

		// Play Current Recoring
		play_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (recordPlay == 0) {
					recordPlay = 1;
					play_button.setBackground(getResources().getDrawable(
							R.drawable.playstop_button));
					record_button.setEnabled(false);
					recordPlay(view);
				} else if (recordPlay == 1) {
					recordPlay = 0;
					play_button.setBackground(getResources().getDrawable(
							R.drawable.play_button));
					record_button.setEnabled(true);
					stopPlay(view);
				}

			}
		});

		/*
		 * Capture image button click event
		 */
		capture_camera_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// create intent with ACTION_IMAGE_CAPTURE action
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

				Log.v(TAG, "PRINT _ 1: " + fileUri);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
				// start the image capture Intent
				startActivityForResult(intent,
						CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
			}
		});

		videorecord_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

				fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
				String URIPATH = fileUri.toString();
				String[] separated = URIPATH.split("/");
				currentVideoName = separated[8];
				Log.v(TAG, "VIDEO PRINT URI : " + currentVideoName);
				// file:///storage/emulated/0/Pictures/lANGUAGEAPP/VID_20140421_133732.mp4

				openPath(fileUri);

				// set video quality
				intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);

				intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the
																	// image
																	// file
																	// name
				videoPreview.setVisibility(View.VISIBLE);
				// start the video capture Intent
				startActivityForResult(intent,
						CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
			}
		});

		Intent i = getIntent();
		nid = i.getStringExtra("nid");
		try {
			Maori_Discover_Word_AudioList_Adapter sa = new Maori_Discover_Word_AudioList_Adapter(
					Maori_Discover_Word_Details.this, nid);
			sa.execute(new String[] { "http://langapp.testarea.co.nz/maoriapi/getNodeAudioSynonyms.php" });
		} catch (Exception e) {

		}

	}

	protected void saveBookMarkDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		ContentValues saveBookMark = new ContentValues();
		Cursor checkFlag = null;
		try {
			checkFlag = mydb.query(BOOKMARK_TABLE, null, "NID = '" + nid + "'",
					null, null, null, null);
		} catch (Exception e) {
		}
		if (checkFlag != null) {
			if (checkFlag.getCount() >= 1) {
				Log.v(TAG, "Excisting Book Mark :" + nid);
			} else {
				try {
					saveBookMark.put("NID", nid);
					saveBookMark.put("english_title", word);
					saveBookMark.put("english_det", word);
					saveBookMark.put("maori_title", maori);
					saveBookMark.put("maori_det", maori);
					saveBookMark.put("category", "word");
					mydb.insert(BOOKMARK_TABLE, null, saveBookMark);
				} catch (Exception e) {

				}
			}
		}
	}

	protected void displayCancelDialog() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(
				Maori_Discover_Word_Details.this);
		builder.setTitle("CANCEL");
		builder.setMessage("Are Sure You Want To Exit...");
		builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				Intent myIntent = new Intent(getBaseContext(),
						Maori_MainActivity.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
			}
		});
		builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(),
						"Add New Words Details..", Toast.LENGTH_LONG).show();
			}
		});
		builder.show();
	}

	protected void loadWordsDetailsList() {
		// TODO Auto-generated method stub
		try {
			// TODO Auto-generated method stub
			Cursor cursor = dbHelper.fetchAllItems();
			// The desired columns to be bound
			String[] columns = new String[] { CaptureFilterAdapter.KEY_WordID,
					CaptureFilterAdapter.KEY_word };
			String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
			// the XML defined views which the data will be bound to
			int[] to = new int[] { R.id.discover_maori_title,
					R.id.discover_english_title };
			// create the adapter using the cursor pointing to the desired data
			// as well as the layout information
			dataAdapter = new SimpleCursorAdapter(this,
					R.layout.language_capture_filter_list_raw, cursor, columns,
					to, 0);

			ListView listViewSearch = (ListView) findViewById(R.id.listViewExcistingSynonyms);
			// Assign adapter to ListView
			listViewSearch.setAdapter(dataAdapter);

			listViewSearch.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> listView, View view,
						int position, long id) {
					// Get the cursor, positioned to the corresponding row in
					// the
					// result set
					Cursor cursor = (Cursor) listView
							.getItemAtPosition(position);

					// Get the state's capital from this row in the database.
					String countryCode = cursor.getString(cursor
							.getColumnIndexOrThrow("word"));
					Toast.makeText(getApplicationContext(), countryCode,
							Toast.LENGTH_SHORT).show();

				}
			});
			Language_App_List_Exapander.getListViewSize(listViewSearch);
			searchfiltertext.addTextChangedListener(new TextWatcher() {

				public void afterTextChanged(Editable s) {
				}

				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
				}

				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					dataAdapter.getFilter().filter(s.toString());
				}
			});

			dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
				public Cursor runQuery(CharSequence constraint) {
					return dbHelper.fetchItemsByName(constraint.toString());
				}
			});
		} catch (Exception e) {
			Log.v(TAG, "Exception*****:" + e);
		}

	}

	/***************** Image capture option handlers **************************/
	/*
	 * Creating file uri to store image/video
	 */
	public Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	/*
	 * returning image / video
	 */
	private static File getOutputMediaFile(int type) {

		// External sdcard location
		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				IMAGE_DIRECTORY_NAME);
		Log.v(TAG, "PRINT _ 4: " + mediaStorageDir);
		upladingFromPath = mediaStorageDir.getAbsolutePath();
		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
						+ IMAGE_DIRECTORY_NAME + " directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
				Locale.getDefault()).format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_" + timeStamp + ".jpg");
			filename = "IMG_" + timeStamp + ".jpg";
			sourceUrl = mediaFile.toString();
			Log.v(TAG, "PRINT _ 5: " + filename);
			Log.v(TAG, "PRINT _ 6: " + sourceUrl);

		} else if (type == MEDIA_TYPE_VIDEO) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "VID_" + timeStamp + ".mp4");
			Log.v(TAG, "PRINT _ 7: " + mediaFile);
		} else {
			return null;
		}

		return mediaFile;
	}

	/*
	 * Display image from a path to ImageView
	 */
	private void previewCapturedImage() {
		try {
			SynonymImages.setVisibility(View.VISIBLE);

			// bimatp factory
			BitmapFactory.Options options = new BitmapFactory.Options();

			// downsizing image as it throws OutOfMemory Exception for larger
			// images
			options.inSampleSize = 8;

			final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
					options);
			SynonymImages.setImageBitmap(bitmap);
			Log.v(TAG, "PRINT _ PREVIEW 1 : " + fileUri.getPath());

		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}

	/*********** Audio Start And Stop Handlers ********************/
	// Stop Playing Audio
	protected void stop(View view) {
		// TODO Auto-generated method stub
		try {
			myRecorder.stop();
			myRecorder.release();
			myRecorder = null;
			Toast.makeText(getApplicationContext(), "Stop recording...",
					Toast.LENGTH_SHORT).show();
		} catch (IllegalStateException e) {
			// it is called before start()
			e.printStackTrace();
		} catch (RuntimeException e) {
			// no valid audio/video data has been received
			e.printStackTrace();
		}
	}

	// Start Playing Audio
	protected void start(View view) {
		// TODO Auto-generated method stub
		try {
			myRecorder.prepare();
			myRecorder.start();
			Toast.makeText(getApplicationContext(), "Start recording...",
					Toast.LENGTH_SHORT).show();
		} catch (IllegalStateException e) {
			// start:it is called before prepare()
			// prepare: it is called after start() or before setOutputFormat()
			e.printStackTrace();
		} catch (IOException e) {
			// prepare() fails
			e.printStackTrace();
		}
		/*
		 * startBtn.setEnabled(false); stopBtn.setEnabled(true);
		 */
	}

	// Play Current Audio
	protected void recordPlay(View view) {
		// TODO Auto-generated method stub
		try {
			myPlayer = new MediaPlayer();
			myPlayer.setDataSource(outputFile);
			myPlayer.prepare();
			myPlayer.start();
			Toast.makeText(getApplicationContext(),
					"Start play the recording..." + outputFile.toString(),
					Toast.LENGTH_SHORT).show();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void stopPlay(View view) {
		// TODO Auto-generated method stub
		try {
			if (myPlayer != null) {
				myPlayer.stop();
				myPlayer.release();
				myPlayer = null;
				Toast.makeText(getApplicationContext(),
						"Stop playing the recording...", Toast.LENGTH_SHORT)
						.show();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/****************** Save Audio Details *****************************/
	protected void saveMediaFileDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		ContentValues enterFileUrl = new ContentValues();
		// Check Previous Language
		Cursor enterFileUrlDetails = null;
		try {
			enterFileUrlDetails = mydb.query(MEDIA_FILE_URL, null,
					"UploadingState !='0'", null, null, null, null);
		} catch (Exception e) {
		}
		if (enterFileUrlDetails != null) {
			if (enterFileUrlDetails.getCount() >= 1) {
				Log.v(TAG, "Excisting Language");
			} else {
				enterFileUrl.put("McategoryId", currentAudioName);
				enterFileUrl.put("MediaFileName", currentAudioName);
				enterFileUrl.put("ResouceDeviceUrl", AudioMainPath);
				enterFileUrl.put("ResouceServerUrl", AudioMainPath);
				enterFileUrl.put("UploadingState", "0");

				mydb.insert(MEDIA_FILE_URL, null, enterFileUrl);
				enterFileUrlDetails.close();
				mydb.close();
			}
		}

	}

	private void getCurrentUserDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor curGetUserInfo = null;
		String queryGetUserInfo;
		try {
			queryGetUserInfo = "SELECT * FROM User";
			curGetUserInfo = mydb.rawQuery(queryGetUserInfo, null);
			if (curGetUserInfo != null) {
				if (curGetUserInfo.getCount() > 0) {
					while (curGetUserInfo.moveToNext()) {
						UserID = curGetUserInfo.getString(11);
					}
				}
			}

		} catch (Exception e) {

		}
		mydb.close();
	}

	public class loadSingleViewSyn extends AsyncTask<String, String, String> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					Maori_Discover_Word_Details.this);
			// Set progressdialog title
			//mProgressDialog.setTitle("Update Likes");
			// Set progressdialog message
			mProgressDialog.setMessage("Processing...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}

		@Override
		protected String doInBackground(String... args) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				httppost = new HttpPost(
						"http://langapp.testarea.co.nz/maoriapi/saveNodeLike.php");
				JSONObject json = new JSONObject();

				String[] LikeRefIdArray = LikeRefId.split("/");
				String synNID = LikeRefIdArray[0]; // NID
				String synUID = LikeRefIdArray[1]; // NID
				// Selected Type ID / content_type_id
				json.put("record1", synNID);
				// Selected UID / added_by
				json.put("record2", synUID);
				// Like Media Category
				json.put("record3", "0");
				
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}

			} catch (Exception e) {
				Log.e("REQUEST :", "Exception LIKES*** :" + e);
			}
			return null;
		}

		@Override
		protected void onPostExecute(String args) {
			mProgressDialog.dismiss();
			new loadSingleView().execute();
		}
	}
	
	
	public class loadSingleViewSynImage extends AsyncTask<String, String, String> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					Maori_Discover_Word_Details.this);
			// Set progressdialog title
			//mProgressDialog.setTitle("Update Likes");
			// Set progressdialog message
			mProgressDialog.setMessage("Processing...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}

		@Override
		protected String doInBackground(String... args) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				httppost = new HttpPost(
						"http://langapp.testarea.co.nz/maoriapi/saveNodeLike.php");
				JSONObject json = new JSONObject();

				String[] LikeRefIdArray = LikeRefId.split("/");
				String synNID = LikeRefIdArray[0]; // NID
				String synUID = LikeRefIdArray[1]; // NID
				// Selected Type ID / content_type_id
				json.put("record1", synNID);
				// Selected UID / added_by
				json.put("record2", synUID);
				// Like Media Category
				json.put("record3", "1");
				
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}

			} catch (Exception e) {
				Log.e("REQUEST :", "Exception LIKES*** :" + e);
			}
			return null;
		}

		@Override
		protected void onPostExecute(String args) {
			mProgressDialog.dismiss();
			reloadTAG = 99;
			new loadSingleView().execute();
		}
	}


	public class loadSingleView extends AsyncTask<String, String, String> {

		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					Maori_Discover_Word_Details.this);
			// Set progressdialog title
			mProgressDialog.setTitle("Download Word Details");
			// Set progressdialog message
			mProgressDialog.setMessage("Loading...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}

		@Override
		protected String doInBackground(String... args) {
			loadCounter = loadCounter + 1;
			
			if(reloadTAG == 99){
				ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				try {
					HttpConnectionParams.setConnectionTimeout(httpParameters,
							timeoutConnection);
					HttpClient httpclient = new DefaultHttpClient(httpParameters);
					HttpPost httppost = new HttpPost("http://langapp.testarea.co.nz/maoriapi/getFilteredBookMarkWords.php");
					JSONObject json = new JSONObject();
					json.put("record1", nid);
					JSONArray postjson = new JSONArray();
					postjson.put(json);
					Log.e("REQUEST :", "999999999999999**** :" + postjson);
					httppost.setHeader("json", json.toString());
					httppost.getParams().setParameter("jsonpost", postjson);
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					HttpResponse response = httpclient.execute(httppost);
					HttpEntity entity = response.getEntity();
					is = entity.getContent();
					if (is != null) {

						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						is.close();
						result = sb.toString();
						if (result != null) {
							Log.e("REQUEST :", "9999999999999999999*****:" + result);
							//arraylist = new ArrayList<HashMap<String, String>>();
							try {
								JSONObject jsonObj = new JSONObject(result);
								jsonarray = jsonObj.getJSONArray("posts");
								for (int i = 0; i < jsonarray.length(); i++) {
									JSONObject c = jsonarray.getJSONObject(i);
									// Get the result of rank
									word = c.getString("word");
									// Get the result of country
									maori = c.getString("wordb");
									// Get the result of population
									nid = c.getString("NID");
									// Get the result of flag
									Source = c.getString("M_Source");
									// Get word category
									MID = c.getString("MID");
									// Get first Name
									first_name = c.getString("first_name");
									// Get last Name
									last_name = c.getString("last_name");
									// Get country
									tribe =c.getString("tribe");
									// Get user image
									userimage = c.getString("userimage");
									// Get Counter Details
									TotalsLikes = c.getString("TotalsLikes");
									TotalsSynonim = c.getString("TotalsSynonim");
									TotalImages = c.getString("TotalImages");
									TotalAudios = c.getString("TotalAudios");
									TotalVideos = c.getString("TotalVideos");
									Log.e("REQUEST :", "PRINT *****:" + word);
									Log.e("REQUEST :", "PRINT *****:" + maori);
									Log.e("REQUEST :", "PRINT *****:" + nid);
									Log.e("REQUEST :", "PRINT *****:" + Source);
									Log.e("REQUEST :", "PRINT *****:" + MID);
									Log.e("REQUEST :", "PRINT *****:" + first_name);
									Log.e("REQUEST :", "PRINT *****:" + last_name);
									Log.e("REQUEST :", "PRINT *****:" + tribe);
									Log.e("REQUEST :", "PRINT *****:" + userimage);
									Log.e("REQUEST :", "PRINT *****:" + TotalsLikes);
									Log.e("REQUEST :", "PRINT *****:" + TotalsSynonim);
									Log.e("REQUEST :", "PRINT *****:" + TotalImages);
									Log.e("REQUEST :", "PRINT *****:" + TotalAudios);
									Log.e("REQUEST :", "PRINT *****:" + TotalVideos);
									// Set the JSON Objects into the array
									//arraylist.add(map);
								}
							}
								catch (Exception e) {
									Log.v(TAG, "***** Exception *****:" + e);
								}
								
						}

					}

				} catch (Exception e) {

				}
			}
			
			else{
				try {
					// Retrieve data from ListViewAdapter on click event
					Intent i = getIntent();
					// Get the result of rank
					word = i.getStringExtra("word");
					// Get the result of country
					maori = i.getStringExtra("maori");
					// Get the result of population
					nid = i.getStringExtra("nid");
					// Get the result of flag
					Source = i.getStringExtra("Source");
					// Get word category
					MID = i.getStringExtra("MID");
					// Get first Name
					first_name = i.getStringExtra("first_name");
					// Get last Name
					last_name = i.getStringExtra("last_name");
					// Get country
					tribe = i.getStringExtra("tribe");
					// Get user image
					userimage = i.getStringExtra("userimage");
					// Get Counter Details
					TotalsLikes = i.getStringExtra("TotalsLikes");
					TotalsSynonim = i.getStringExtra("TotalsSynonim");
					TotalImages = i.getStringExtra("TotalImages");
					TotalAudios = i.getStringExtra("TotalAudios");
					TotalVideos = i.getStringExtra("TotalVideos");
					// Download the Image from the result URL given by flag
					Log.e("REQUEST :", "nid ********* :" + nid);
					Log.e("REQUEST :", "loadCounter **** :" + loadCounter);
					Log.e("REQUEST :", "TotalsSynonim **** :" + TotalsSynonim);
					URL url = new URL(Source);
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.setDoInput(true);
					conn.connect();
					/*
					 * InputStream is = conn.getInputStream(); bmImg =
					 * BitmapFactory.decodeStream(is);
					 */
					Log.e("REQUEST :", "@@@@@@@@@@@@@@@@@@@  :" + Source);
					
				
				} catch (IOException e) {
					Log.e("Error", e.getMessage());
					e.printStackTrace();
				}
			}
		

			/******** Listing Words Synonyms *******************************/
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(
						"http://langapp.testarea.co.nz/maoriapi/getCurrentWordSynonyms.php");
				JSONObject json = new JSONObject();
				json.put("record1", nid);
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST :", "request Word Synonim**** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {
						Log.e("REQUEST :", "Synonym Res DDD*****:" + result);
						arraylist = new ArrayList<HashMap<String, String>>();
						try {
							JSONObject jsonObj = new JSONObject(result);
							jsonarray = jsonObj.getJSONArray("posts");
							int cynonimval = 0;
							for (int i = 0; i < jsonarray.length(); i++) {
								JSONObject c = jsonarray.getJSONObject(i);
								HashMap<String, String> map = new HashMap<String, String>();
								TotalsSynonimValue = TotalsSynonimValue + 1;
								Log.e("REQUEST :", "cynonimval(C) ****:"
										+ cynonimval);
								map.put("Description_a",c.getString("Description_a"));
								map.put("Description_b",
										c.getString("Description_b"));
								map.put("first_namesuser",
										c.getString("first_namesuser"));
								map.put("last_nameuser",
										c.getString("last_nameuser"));
								map.put("tribeuser", c.getString("tribeuser"));
								// Sorce URL
								map.put("userimageuser",
										c.getString("userimageuser"));
								map.put("UIDuser", c.getString("UIDuser"));
								map.put("TotalsLikesSyn",
										c.getString("TotalsLikesSyn"));
								map.put("SYNNID", c.getString("SYNNID"));
								// Set the JSON Objects into the array
								arraylist.add(map);
							}
						} catch (Exception e) {
							Log.v(TAG, "***** Exception *****:" + e);
						}

					}

				}

			} catch (Exception e) {

			}
			// http://langapp.testarea.co.nz/maoriapi/getNodeAudioSynonyms.php
			/******** Listing Video Synonyms *******************************/
			ArrayList<NameValuePair> nameValuePairsVideo = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(
						"http://langapp.testarea.co.nz/maoriapi/getNodeVideosSynonyms.php");
				JSONObject json = new JSONObject();
				json.put("record1", nid);
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST :", "request Video**** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsVideo));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {
						Log.e("REQUEST :", "Synonym Video *****:" + result);
						videoArrayList = new ArrayList<HashMap<String, String>>();
						try {
							JSONObject jsonObj = new JSONObject(result);
							jsonarray = jsonObj.getJSONArray("posts");
							for (int i = 0; i < jsonarray.length(); i++) {
								TotalsSynonimVideoValue = TotalsSynonimVideoValue + 1;

								JSONObject c = jsonarray.getJSONObject(i);
								HashMap<String, String> map = new HashMap<String, String>();
								map.put("M_Source", c.getString("M_Source"));
								// Set the JSON Objects into the array
								videoArrayList.add(map);
							}
						} catch (Exception e) {
							Log.v(TAG, "***** Exception *****:" + e);
						}
					}

				}

			} catch (Exception e) {

			}
			/******** Listing Images Synonyms *******************************/
			
			ArrayList<NameValuePair> nameValuePairsImages = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(
						"http://langapp.testarea.co.nz/maoriapi/getNodeImageSynonyms.php");
				JSONObject json = new JSONObject();
				json.put("record1", nid);
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST :", "request Images**** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsImages));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {
						Log.e("REQUEST :", "Synonym Images 1000*****:" + result);
						imagesArrayList = new ArrayList<HashMap<String, String>>();
						try {
							JSONObject jsonObj = new JSONObject(result);
							jsonarray = jsonObj.getJSONArray("posts");
							for (int i = 0; i < jsonarray.length(); i++) {
								TotalsSynonimImagesValue = TotalsSynonimImagesValue + 1;

								JSONObject c = jsonarray.getJSONObject(i);
								HashMap<String, String> map = new HashMap<String, String>();
								map.put("IMAGENM_ID", c.getString("IMAGENM_ID"));
								map.put("IMAGENID", c.getString("IMAGENID"));
								map.put("IMAGEMID", c.getString("IMAGEMID"));
								map.put("IMAGEUID", c.getString("IMAGEUID"));
								map.put("IMAGEM_Source", c.getString("IMAGEM_Source"));
								map.put("IMAGEfirst_name", c.getString("IMAGEfirst_name"));
								map.put("IMAGElast_name", c.getString("IMAGElast_name"));
								map.put("IMAGETotalsLikes", c.getString("IMAGETotalsLikes"));
								// Set the JSON Objects into the array
								imagesArrayList.add(map);
							}
						} catch (Exception e) {
							Log.v(TAG, "***** Exception *****:" + e);
						}
					}

				}

			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(String args) {
			// Locate the TextViews in singleitemview.xml
			
		/*	try {
				Maori_Discover_Word_AudioList_Adapter sa = new Maori_Discover_Word_AudioList_Adapter(
						Maori_Discover_Word_Details.this, nid);
				sa.execute(new String[] { "http://langapp.testarea.co.nz/maoriapi/getNodeAudioSynonyms.php" });
			} catch (Exception e) {
				Log.e("postjson", "Exception :" + e);
			}*/

			TextView memdiscover_det_title = (TextView) findViewById(R.id.memdiscover_det_title);
			TextView memdiscover_det_subtitle = (TextView) findViewById(R.id.memdiscover_det_subtitle);
			ImageView memdiscover_det_image = (ImageView) findViewById(R.id.memdiscover_det_image);

			TextView uploaduserfname = (TextView) findViewById(R.id.uploaduserfname);
			TextView uploaduserlname = (TextView) findViewById(R.id.uploaduserlname);
			ImageView upuserimage = (ImageView) findViewById(R.id.upuserimage);
			Button upusercountry = (Button) findViewById(R.id.upusercountry);

			// Set results to the TextViews
			memdiscover_det_title.setText(word);
			memdiscover_det_subtitle.setText(maori);
			uploaduserfname.setText(first_name);
			uploaduserlname.setText(last_name);
			upusercountry.setText(tribe);
			
			int loader = R.drawable.ic_launcher;
			     try{
				   ImageLoader imgLoader = new ImageLoader(getApplicationContext());
				   imgLoader.DisplayImage(Source,memdiscover_det_image);
				   imgLoader.DisplayImage(userimage, upuserimage);
				}
				 catch (Exception e) {
					 
				 }
			
			memdiscover_det_image.setImageBitmap(bmImg);
			upuserimage.setImageBitmap(userbmImg);

			// TotalsLikes,TotalsSynonim,TotalImages,TotalAudios,TotalVideos
			Button wordsynonyms = (Button) findViewById(R.id.wordsynonyms);
			Button wordaudio = (Button) findViewById(R.id.wordaudio);
			Button wordimages = (Button) findViewById(R.id.wordimages);
			Button wordvideo = (Button) findViewById(R.id.wordvideo);

			wordsynonyms.setText(TotalsSynonimValue + "\nSynonyms");
			wordaudio.setText(TotalAudios + "\nAudio");
			wordimages.setText(TotalsSynonimImagesValue + "\nImages");
			wordvideo.setText(TotalVideos + "\nVideos");

			/******* List Synonyms **********/
			listview = (ListView) findViewById(R.id.listViewSynonyms);
			// Pass the results into ListViewAdapter.java
			adapter = new Maori_Discover_Word_Details_Adapter(
					Maori_Discover_Word_Details.this, arraylist);
			// Binds the Adapter to the ListView
			listview.setAdapter(adapter);
			// Close the progressdialog
			mProgressDialog.dismiss();
			Language_App_List_Exapander.getListViewSize(listview);

			/*********** List Audio ********************/
			// Maori_Discover_Word_ImageList_Adapter adapterImages;

			listViewImageSynonyms = (ListView) findViewById(R.id.listViewImageSynonyms);
			// Pass the results into ListViewAdapter.java
			adapterImages = new Maori_Discover_Word_ImageList_Adapter(
					Maori_Discover_Word_Details.this, imagesArrayList);
			// Binds the Adapter to the ListView
			listViewImageSynonyms.setAdapter(adapterImages);
			// Close the progressdialog
			mProgressDialog.dismiss();
			Language_App_List_Exapander.getListViewSize(listViewImageSynonyms);

			// Maori_Discover_Word_VideoList_Adapter adapterVideos;
			listViewVideoSynonyms = (ListView) findViewById(R.id.listViewVideoSynonyms);
			// Pass the results into ListViewAdapter.java
			adapterVideos = new Maori_Discover_Word_VideoList_Adapter(
					Maori_Discover_Word_Details.this, videoArrayList);
			// Binds the Adapter to the ListView
			listViewVideoSynonyms.setAdapter(adapterVideos);
			// Close the progressdialog
			mProgressDialog.dismiss();
			Language_App_List_Exapander.getListViewSize(listViewVideoSynonyms);
			TotalsSynonimValue = 0;
			TotalsSynonimImagesValue = 0;

		}
	}

	/********************************************************************
	 ************* UPLOADING SYNONIMS
	 *************************************/
	private class UploadingSynonimDetails extends AsyncTask<Void, Void, Void> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					Maori_Discover_Word_Details.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading Synonyms");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				httppost = new HttpPost(saveSaveSynonimAUrl);
				JSONObject json = new JSONObject();
				// Selected Type ID / content_type_id
				json.put("record1", "1");
				// Selected UID / added_by
				json.put("record2", UserID);
				// Record Added Date /added_on
				json.put("record3", getAddDateTimeString().toString());
				// Record dialect_id
				json.put("record4", "1");
				// Curent Node Category ID
				json.put("record5", MID);
				// Curent Node Category LINKNID / parent node id
				json.put("record6", nid);
				// Curent LID - language ids
				json.put("record7", "1=2"); // LID
				// Curent uploading contents
				json.put("record8", etmaorisynonimword.getText().toString()
						+ "=" + etenglishsynonimword.getText().toString()); // LID
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				Log.e("postjson", "postjson XXX :" + postjson.toString()
						+ " = " + MID);

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			listViewSynonyms.setVisibility(LinearLayout.VISIBLE);
			capturesynonims.setVisibility(LinearLayout.GONE);
			searchviewarea.setVisibility(LinearLayout.GONE);
			capturesynonimsaudio.setVisibility(LinearLayout.GONE);
			capturesynonimsimages.setVisibility(LinearLayout.GONE);
			captureActionControllers.setVisibility(LinearLayout.GONE);
			etmaorisynonimword.setText("");
			etenglishsynonimword.setText("");
			final AlertDialog alertDialog = new AlertDialog.Builder(
					Maori_Discover_Word_Details.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("Uploaded");
			// Setting Dialog Message
			alertDialog.setMessage("Upload Completed..");
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					new loadSingleView().execute();
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			mProgressDialog.dismiss();
		}
	}

	/************** Uploading Image Details ********************************/
	private class UploadImageDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					Maori_Discover_Word_Details.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading Image Details");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				httppost = new HttpPost(
						"http://langapp.testarea.co.nz/maoriapi/saveSynonymImages.php");
				JSONObject json = new JSONObject();
				// Sending Node ID
				json.put("record1", nid);
				// Server URL
				json.put("record2",
						"http://langapp.testarea.co.nz/lanappimage/" + filename);

				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				Log.e("postjson", "postjson XXX :" + postjson.toString()
						+ " = " + MID);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}
			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			new UploadTaskImages().execute();
		}
	}

	/************** Uploading Video Details ********************************/
	private class UploadVideoDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					Maori_Discover_Word_Details.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading Video Details");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				httppost = new HttpPost(
						"http://langapp.testarea.co.nz/maoriapi/saveSynonymVideo.php");
				JSONObject json = new JSONObject();
				// Sending Node ID
				json.put("record1", nid);
				// Server URL
				json.put("record2",
						"http://langapp.testarea.co.nz/lanappvideo/"
								+ currentVideoName);
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				Log.e("postjson", "postjson XXX :" + postjson.toString()
						+ " = " + MID);

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}
			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			new UploadTaskVideo().execute();
		}
	}

	/************** Uploading Audio Details ********************************/
	private class UploadAudioDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					Maori_Discover_Word_Details.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading Audio Details");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				httppost = new HttpPost(
						"http://langapp.testarea.co.nz/maoriapi/saveSynonymAudio.php");
				JSONObject json = new JSONObject();
				// Sending Node ID
				json.put("record1", nid);
				// Server URL
				json.put("record2",
						"http://langapp.testarea.co.nz/lanappaudio/"
								+ currentAudioName);

				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				Log.e("postjson", "postjson XXX :" + postjson.toString()
						+ " = " + MID);

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}
			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			new UploadTask().execute();
		}
	}

	private class UploadingWordsDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					Maori_Discover_Word_Details.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading Synonyms");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				httppost = new HttpPost(saveSaveSynonimAUrl);
				JSONObject json = new JSONObject();
				// Selected Type ID / content_type_id
				json.put("record1", "1");
				// Selected UID / added_by
				json.put("record2", UserID);
				// Record Added Date /added_on
				json.put("record3", getAddDateTimeString().toString());
				// Record dialect_id
				json.put("record4", "1");
				// Curent Node Category ID
				json.put("record5", MID);
				// Curent Node Category LINKNID / parent node id
				json.put("record6", nid);
				// Curent LID - language ids
				json.put("record7", "1=2"); // LID
				// Curent uploading contents
				json.put("record8", etmaorisynonimword.getText().toString()
						+ "=" + etenglishsynonimword.getText().toString()); // LID

				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				Log.e("postjson", "postjson :" + postjson.toString());

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();

		}

	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	private String getAudiorecording() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyyMMddHHmmss");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	public boolean isNetworkAvailable() {
		ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**************** Uploading Audio Via FTP ************************/
	class UploadTask extends AsyncTask<Void, Void, Void> {

		ProgressDialog pDialog;
		Boolean uploadStat;

		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(Maori_Discover_Word_Details.this);
			pDialog.setMessage("Uploading Audio Files...");
			pDialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// /Pictures/lANGUAGEAPP
			upladingFromPath = "/storage/emulated/0/";
			Log.v(TAG, "data uploading 1 : " + upladingFromPath);
			Log.v(TAG, "data uploading 2 : " + currentAudioName);
			Log.v(TAG, "data uploading 3 : " + desDirectory);

			uploadStat = new UploadToFtpAudio().ftpUpload1(upladingFromPath,
					currentAudioName, desDirectory);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (uploadStat) {

					} else {
						AlertDialog.Builder b = new AlertDialog.Builder(
								Maori_Discover_Word_Details.this);
						b.setMessage("Upload Failed.");
						b.show();
					}

				}
			});
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (null != pDialog && pDialog.isShowing()) {
				pDialog.dismiss();
			}
			super.onPostExecute(result);
			final AlertDialog alertDialog = new AlertDialog.Builder(
					Maori_Discover_Word_Details.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("DATA ULOADED SUCCESS");
			// Setting Dialog Message
			alertDialog.setMessage("Audio Uploading Completed...");
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					capturesynonims.setVisibility(LinearLayout.GONE);
					captureActionControllers.setVisibility(LinearLayout.GONE);
					capturesynonimsaudio.setVisibility(LinearLayout.GONE);
					capturesynonimsimages.setVisibility(LinearLayout.GONE);
					listViewSynonyms.setVisibility(LinearLayout.VISIBLE);
					if (AudioTag == 202) {
						wordsynonyms.setBackgroundResource(R.color.CLR_ORANGE);
						btnviewsynonims.setImageResource(R.drawable.iconj);
						wordimages.setBackgroundResource(R.color.CLR_SKYBLUE);
						wordaudio.setBackgroundResource(R.color.CLR_SKYBLUE);
						listViewSynonyms.setVisibility(LinearLayout.VISIBLE);
						SynonimTag = 202;
					}

					new loadSingleView().execute();
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}
	}

	/**************** Uploading Images Via FTP ************************/
	class UploadTaskImages extends AsyncTask<Void, Void, Void> {

		ProgressDialog pDialog;
		Boolean uploadStat;

		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(Maori_Discover_Word_Details.this);
			pDialog.setMessage("Uploading Image Files...");
			pDialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			upladingFromPath = "/storage/emulated/0/Pictures/lANGUAGEAPP/";
			Log.v(TAG, "data uploading 1 : " + upladingFromPath);
			Log.v(TAG, "data uploading 2 : " + filename);
			Log.v(TAG, "data uploading 3 : " + desDirectory);

			uploadStat = new UploadToFtp().ftpUpload1(upladingFromPath,
					filename, desDirectory);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (uploadStat) {

					} else {
						AlertDialog.Builder b = new AlertDialog.Builder(
								Maori_Discover_Word_Details.this);
						b.setMessage("Upload Failed.");
						b.show();
					}

				}
			});
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (null != pDialog && pDialog.isShowing()) {
				pDialog.dismiss();
			}
			super.onPostExecute(result);

			final AlertDialog alertDialog = new AlertDialog.Builder(
					Maori_Discover_Word_Details.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("DATA ULOADED SUCCESS");
			// Setting Dialog Message
			alertDialog.setMessage("Image Uploading Completed...");
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					capturesynonims.setVisibility(LinearLayout.GONE);
					captureActionControllers.setVisibility(LinearLayout.GONE);
					capturesynonimsaudio.setVisibility(LinearLayout.GONE);
					capturesynonimsimages.setVisibility(LinearLayout.GONE);
					listViewSynonyms.setVisibility(LinearLayout.VISIBLE);
					if (ImageTag == 202) {
						wordsynonyms.setBackgroundResource(R.color.CLR_ORANGE);
						btnviewsynonims.setImageResource(R.drawable.iconj);
						wordimages.setBackgroundResource(R.color.CLR_SKYBLUE);
						listViewSynonyms.setVisibility(LinearLayout.VISIBLE);
						SynonimTag = 202;
					}
					new loadSingleView().execute();
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}
	}

	/**
	 * Receiving activity result method will be called after closing the camera
	 * */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// if the result is capturing Image
		if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				// successfully captured the image
				// display it in image view
				previewCapturedImage();
			} else if (resultCode == RESULT_CANCELED) {
				// user cancelled Image capture
				Toast.makeText(getApplicationContext(),
						"User cancelled image capture", Toast.LENGTH_SHORT)
						.show();
			} else {
				// failed to capture image
				Toast.makeText(getApplicationContext(),
						"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
						.show();
			}
		} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
			camvideoparent.setVisibility(View.VISIBLE);
			if (resultCode == RESULT_OK) {
				// video successfully recorded
				// preview the recorded video
				camvideoparent.setVisibility(View.VISIBLE);
				previewVideo();
			} else if (resultCode == RESULT_CANCELED) {
				// user cancelled recording
				Toast.makeText(getApplicationContext(),
						"User cancelled video recording", Toast.LENGTH_SHORT)
						.show();
			} else {
				// failed to record video
				Toast.makeText(getApplicationContext(),
						"Sorry! Failed to record video", Toast.LENGTH_SHORT)
						.show();
			}
		}

		else if (resultCode == Activity.RESULT_OK) {
			if (resultCode == Activity.RESULT_OK) {
				selectedImageUri = data.getData();
				Log.e("Bitmap", "selectedImageUri :" + selectedImageUri);
				try {
					// OI FILE Manager
					filemanagerstring = selectedImageUri.getPath();

					// MEDIA GALLERY
					selectedImagePath = getPath(selectedImageUri);

					if (selectedImagePath != null) {
						filePath = selectedImagePath;
					} else if (filemanagerstring != null) {
						filePath = filemanagerstring;
					} else {
						Toast.makeText(getApplicationContext(), "Unknown path",
								Toast.LENGTH_LONG).show();
						Log.e("Bitmap", "Unknown path");
					}

					if (filePath != null) {
						decodeFile(filePath);
					} else {
						bitmap = null;
					}
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Internal error",
							Toast.LENGTH_LONG).show();
					Log.e(e.getClass().getName(), e.getMessage(), e);
				}
			}
		}

	}

	/*************** Image Capture Activities ******************/
	private String getPath(Uri selectedImageUri) throws FileNotFoundException {

		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
				null);

		if (cursor != null) {

			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

			cursor.moveToFirst();
			/* Uri uri = Uri.parse(cursor.getString(1)); */

			return cursor.getString(column_index);
		} else
			return null;
	}

	private String decodeFile(String filePath) {
		// Decode image size
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, o);

		// The new size we want to scale to
		final int REQUIRED_SIZE = 1024 * 4;

		// Find the correct scale value. It should be the power of 2.
		int width_tmp = o.outWidth, height_tmp = o.outHeight;
		int scale = 1;
		while (true) {
			if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
				break;
			width_tmp /= 2;
			height_tmp /= 2;
			scale *= 2;
		}

		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize = scale;

		bitmap = BitmapFactory.decodeFile(filePath, o2);
		SynonymImages.setImageBitmap(bitmap);

		Calendar c = Calendar.getInstance();
		SimpleDateFormat dfsigdate = new SimpleDateFormat("yyyyMMddHHmmss");
		String formattedSigDatep = dfsigdate.format(c.getTime());
		tempDir = "/data/data/com.maori.languageapp/CAMIMAGES/";
		Log.v(TAG, "XXX tempDir : " + tempDir);
		prepareDirectory();
		String filenamepath = tempDir + getAudiorecording().toString() + ".png";
		currentImageName = getAudiorecording().toString() + ".png";

		Log.v(TAG, "XXX tempDir : " + filenamepath);
		File dest = new File(filenamepath);
		try {
			FileOutputStream out = new FileOutputStream(dest);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			Log.v(TAG, "Exception : " + e);
		}

		return filePath;
	}

	private boolean prepareDirectory() {
		try {
			if (makedirs()) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(
					this,
					"Could not initiate File System.. Is Sdcard mounted properly?",
					Toast.LENGTH_SHORT).show();
			return false;
		}
	}

	private boolean makedirs() {
		File tempdir = new File(tempDir);
		if (!tempdir.exists())
			tempdir.mkdirs();

		if (tempdir.isDirectory()) {

		}
		return (tempdir.isDirectory());
	}

	/************* Video Recording and Preview *************************/
	/**
	 * ------------ Helper Methods ----------------------
	 * */

	public void openPath(Uri uri) {
		InputStream is = null;
		try {
			is = getContentResolver().openInputStream(uri);

			// Convert your stream to data here
			is.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * Previewing recorded video
	 */
	private void previewVideo() {
		try {
			// hide image preview
			// imgPreview.setVisibility(View.GONE);
			capturesynonimsvideo.setVisibility(LinearLayout.VISIBLE);
			camvideoparent.setVisibility(LinearLayout.VISIBLE);
			// camvideoparent.setVisibility(View.VISIBLE);
			videoPreview.setVideoPath(fileUri.getPath());
			// start playing
			videoPreview.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**************** Uploading Video Via FTP ************************/
	class UploadTaskVideo extends AsyncTask<Void, Void, Void> {

		ProgressDialog pDialog;
		Boolean uploadStat;

		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(Maori_Discover_Word_Details.this);
			pDialog.setMessage("Uploading Video Files...");
			pDialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// /Pictures/lANGUAGEAPP
			upladingFromPath = "/storage/emulated/0/Pictures/lANGUAGEAPP/";
			Log.v(TAG, "data uploading 1 : " + upladingFromPath);
			Log.v(TAG, "data uploading 2 : " + currentVideoName);
			Log.v(TAG, "data uploading 3 : " + desDirectory);

			uploadStat = new UploadToFtpVideo().ftpUpload1(upladingFromPath,
					currentVideoName, desDirectory);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (uploadStat) {

					} else {
						AlertDialog.Builder b = new AlertDialog.Builder(
								Maori_Discover_Word_Details.this);
						b.setMessage("Upload Failed.");
						b.show();
					}

				}
			});
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (null != pDialog && pDialog.isShowing()) {
				pDialog.dismiss();
			}
			super.onPostExecute(result);

			final AlertDialog alertDialog = new AlertDialog.Builder(
					Maori_Discover_Word_Details.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("DATA ULOADED SUCCESS");
			// Setting Dialog Message
			alertDialog.setMessage("Video Uploading Completed...");
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					capturesynonims.setVisibility(LinearLayout.GONE);
					captureActionControllers.setVisibility(LinearLayout.GONE);
					capturesynonimsaudio.setVisibility(LinearLayout.GONE);
					capturesynonimsimages.setVisibility(LinearLayout.GONE);
					capturesynonimsvideo.setVisibility(LinearLayout.GONE);
					camvideoparent.setVisibility(LinearLayout.GONE);
					listViewSynonyms.setVisibility(LinearLayout.VISIBLE);
					if (VideoTag == 202) {
						wordsynonyms.setBackgroundResource(R.color.CLR_ORANGE);
						btnviewsynonims.setImageResource(R.drawable.iconj);
						wordimages.setBackgroundResource(R.color.CLR_SKYBLUE);
						wordvideo.setBackgroundResource(R.color.CLR_SKYBLUE);
						listViewSynonyms.setVisibility(LinearLayout.VISIBLE);
						SynonimTag = 202;
					}
					new loadSingleView().execute();
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;

		}
	}

	/**************** Uploading Book Mark details ***************************/
	private class UploadBookMarkDetails extends AsyncTask<Void, Void, Void> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);

				if (HeaderBtnTag == 100) {
					httppost = new HttpPost(
							"http://langapp.testarea.co.nz/maoriapi/saveNodeBookMark.php");
				} else if (HeaderBtnTag == 300) {
					httppost = new HttpPost(
							"http://langapp.testarea.co.nz/maoriapi/saveNodeLike.php");
				}

				JSONObject json = new JSONObject();
				// Selected Type ID / content_type_id
				json.put("record1", nid);
				// Selected UID / added_by
				json.put("record2", UserID);

				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			HeaderBtnTag = 0;
			Toast.makeText(getApplicationContext(), "Flag Success..",
					Toast.LENGTH_LONG).show();
		}
	}

	/**********************************************************************/

	public class UploadSynonimLikes extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			HeaderBtnTag = 0;
			arraylist.clear();
			// ******** Listing Words Synonyms
			// *******************************//*
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(
						"http://langapp.testarea.co.nz/maoriapi/getCurrentWordSynonyms.php");
				JSONObject json = new JSONObject();
				String[] LikeRefIdArray = LikeRefId.split("/");
				
				String synNID = LikeRefIdArray[0]; // NID
				String synUID = LikeRefIdArray[1]; // NID
				Log.e("@@@@@@@@@@@", "synNID@@@@ 100:" + synNID);
				Log.e("@@@@@@@@@@@", "synUID@@@@ 200:" + synUID);
				json.put("record1", synNID);
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {
						Log.e("REQUEST :", "Synonym Res DDD*****:" + result);
						arraylist = new ArrayList<HashMap<String, String>>();
						try {
							JSONObject jsonObj = new JSONObject(result);
							jsonarray = jsonObj.getJSONArray("posts");
							int cynonimval = 0;
							for (int i = 0; i < jsonarray.length(); i++) {
								JSONObject c = jsonarray.getJSONObject(i);
								HashMap<String, String> map = new HashMap<String, String>();
								TotalsSynonimValue = TotalsSynonimValue + 1;

								map.put("Description_a",
										c.getString("Description_a"));
								map.put("Description_b",
										c.getString("Description_b"));
								map.put("first_namesuser",
										c.getString("first_namesuser"));
								map.put("last_nameuser",
										c.getString("last_nameuser"));
								map.put("tribeuser", c.getString("tribeuser"));
								// Sorce URL
								map.put("userimageuser",
										c.getString("userimageuser"));
								map.put("UIDuser", c.getString("UIDuser"));
								map.put("TotalsLikesSyn",
										c.getString("TotalsLikesSyn"));
								map.put("SYNNID", c.getString("SYNNID"));
								Log.e("REQUEST :",
										"TOT LIKES ****:"
												+ c.getString("TotalsLikesSyn"));
								// Set the JSON Objects into the array
								arraylist.add(map);
							}
						} catch (Exception e) {
							Log.v(TAG, "***** Exception DJ 2*****:" + e);
						}

					}

				}

			} catch (Exception e) {
				Log.e("@@@@@@@@@@@", "Exception@@@@@@@@@@@:" + e);
			}

			// ******* List Synonyms **********//*
			/*listview = (ListView) findViewById(R.id.listViewSynonyms);
			// Pass the results into ListViewAdapter.java
			adapter = new Maori_Discover_Word_Details_Adapter(
					Maori_Discover_Word_Details.this, arraylist);
			// Binds the Adapter to the ListView
			listview.setAdapter(adapter);
			// Close the progressdialog

			Language_App_List_Exapander.getListViewSize(listview);
*/

			return null;
		}

		@Override
		protected void onPostExecute(String args) {
			new loadSingleView().execute();
		}
	}

	/**********************************************************************/
	@Override
	public void onBackPressed() {
		displayCancelDialog();
	}

	// ***********Memory Handling****************
	@Override
	protected void onStop() {
		super.onStop();
	}

	// Fires after the OnStop() state
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			trimCache(this);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void trimCache(Context context) {
		try {
			File dir = context.getCacheDir();
			if (dir != null && dir.isDirectory()) {
				deleteDir(dir);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static boolean deleteDir(File dir) {
		if (dir != null && dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}

		// The directory is now empty so delete it
		return dir.delete();
	}
	
	public class loadDefaultImage extends AsyncTask<String, String, String> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					Maori_Discover_Word_Details.this);
			// Set progressdialog title
			//mProgressDialog.setTitle("Update Likes");
			// Set progressdialog message
			mProgressDialog.setMessage("Processing...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}

		@Override
		protected String doInBackground(String... args) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				httppost = new HttpPost(
						"http://langapp.testarea.co.nz/maoriapi/saveDefaultImage.php");
				JSONObject json = new JSONObject();

				String[] LikeRefIdArray = LikeRefId.split("/");
				reloadREFNO = LikeRefIdArray[0]; // NID
				String synUID = LikeRefIdArray[1]; // NID
				String synMID = LikeRefIdArray[2]; // NID
				// Selected Type ID / content_type_id
				json.put("record1", reloadREFNO);
				// Selected UID / added_by
				json.put("record2", synUID);
				// Like Media Category
				json.put("record3", synMID);
				
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}

			} catch (Exception e) {
				Log.e("REQUEST :", "Exception LIKES*** :" + e);
			}
			return null;
		}

		@Override
		protected void onPostExecute(String args) {
			mProgressDialog.dismiss();
			reloadTAG = 99;
			new loadSingleView().execute();
		}
	}
}
